import {
  getMaterialShortageByPage,
  addMaterialShortage,
  updateMaterialShortage,
  delMaterialShortage,
  exportMaterialShortage,
} from '@/services/material/materialShortage';
import ShortageMiddle from '../product/shortageMiddle';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Tabs, Form, Input, message, Modal, Tree } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import PurchaseOrder from '../product/purchaseOrder';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { tableSearchPublicConfig } from '@/utils/filterUtils';

const MaterialShortage: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [isShort, setIsShort] = useState<number>(1);
  const [form] = Form.useForm();
  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,

      width: 150,
    },
    {
      title: '预计到货日期',
      dataIndex: 'expectedDeliveryTime',
      search: false,

      align: 'center',
      sorter: true,
    },
    {
      title: '预计到货日期',
      dataIndex: 'expectedDeliveryTime',
      valueType: 'dateRange',
      hideInTable: true,
      align: 'center',
      sorter: true,
    },
    {
      title: '项目id',
      dataIndex: 'infoId',
      align: 'center',
      sorter: true,
      search: false,
      hideInTable: true,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      align: 'center',
      sorter: true,
    },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      align: 'center',
      sorter: true,
    },
    {
      title: '物料规格',
      dataIndex: 'materialSpec',
      align: 'center',
      sorter: true,
    },
    {
      title: '物料类型',
      dataIndex: 'materialType',
      align: 'center',
      sorter: true,
    },
    {
      title: '单位',
      dataIndex: 'unit',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '当前批次',
      dataIndex: 'currentBatch',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '批次总数',
      dataIndex: 'batchCount',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '缺货数量',
      dataIndex: 'lackQty',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,
      width: 120,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      align: 'center',
      sorter: true,
    },
    /*     {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
     align: 'center',sorter: true, 
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              expectedDeliveryTime: record.expectedDeliveryTime,
              infoId: record.infoId,
              materialCode: record.materialCode,
              materialName: record.materialName,
              materialSpec: record.materialSpec,
              materialType: record.materialType,
              projectName: record.projectName,
              unit: record.unit,
              batchCount: record.batchCount,
              currentBatch: record.currentBatch,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delMaterialShortage({ id: record.id });
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    }, */
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const result = await addMaterialShortage(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateMaterialShortage(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current!.reload();
  };
  type tabsType = {
    key: string;
    name: string;
    label: string;
    content: JSX.Element;
  };
  const items1: tabsType[] = [
    {
      key: '0',
      name: 'tab1',
      label: `分料前缺料`,
      content: <PurchaseOrder isShort={isShort} />,
    },
    {
      key: '1',
      name: 'tab2',
      label: '生产中缺料',
      content: (
        <div>
          <ShortageMiddle />
        </div>
      ),
    },
    {
      key: '2',
      name: 'tab3',
      label: `完工后缺料`,
      content: (
        <div>
          <ProTable
            search={{
              labelWidth: 100,
              ...tableSearchPublicConfig,
            }}
            headerTitle="完工后缺料查询"
            actionRef={actionRef} //用于触发刷新操作等，看api
            rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
            formRef={ref}
            toolBarRender={(action, { selectedRows }) => [
              ,
              /*               <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  setCreateOrUpdate(false);
                  setFormTitle('新建');
                  form.resetFields();
                  setModalVisit(true);
                }}
                type="primary"
              >
                新建
              </Button> */ <Button
                key="button"
                icon={<PlusOutlined />}
                onClick={() => {
                  const filters = filterTranNew(ref.current.getFieldsValue());
                  exportMaterialShortage({
                    current: 1,
                    pageSize: 5000,
                    filters: filters,
                  }).then((res) => {
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    aLink.setAttribute('download', `MaterialShortage.xls`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                }}
                type="primary"
              >
                导出
              </Button>,
            ]}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters = filterTranNew(params);
              const result = await getMaterialShortageByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              result.data.content.map((item: any) => {
                item.createTime = item.createTime.split(' ')[0]; //处理日期，只保留到日
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            columns={columns}
            scroll={{ x: 2000, y: 350 }}
            rowSelection={{}}
          />
        </div>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <Tabs
        type="card"
        defaultActiveKey="0"
        // onChange={(e) => {
        //   setPageState(String(Number(e) - 1));
        //   console.log(String(Number(e) - 1), 'page');
        // }}
        items={items1.map((item, i) => {
          const id = String(i + 1);
          return {
            label: item.label,
            key: id,
            children: <div>{item.content}</div>,
          };
        })}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="expectedDeliveryTime"
          label="预计到货日期"
          rules={[{ required: true, message: 'Please input your expectedDeliveryTime!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="materialCode"
          label="物料编号"
          rules={[{ required: true, message: 'Please input your materialCode!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="infoId"
          label="项目id"
          rules={[{ required: true, message: 'Please input your infoId!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="materialName"
          label="物料名称"
          rules={[{ required: true, message: 'Please input your materialName!' }]}
          disabled={createOrUpdate}
        />
        {/*         <ProFormText
          name="materialCode"
          label="物料编号"
          rules={[{ required: true, message: 'Please input your materialCode!' }]}
          disabled={createOrUpdate}
        /> */}
        <ProFormText
          name="materialSpec"
          label="物料规格"
          rules={[{ required: true, message: 'Please input your materialSpec!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="materialType"
          label="物料类型"
          rules={[{ required: true, message: 'Please input your materialType!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="projectName"
          label="项目名称"
          rules={[{ required: true, message: 'Please input your projectName!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="unit"
          label="单位"
          rules={[{ required: true, message: 'Please input your unit!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="batchCount"
          label="批次总数"
          rules={[{ required: true, message: 'Please input your batchCount!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="currentBatch"
          label="当前批次"
          rules={[{ required: true, message: 'Please input your currentBatch!' }]}
          disabled={createOrUpdate}
        />
        <ProFormText
          name="lackQty"
          label="缺货数量"
          rules={[{ required: true, message: 'Please input your lackQty!' }]}
          disabled={createOrUpdate}
        />
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default MaterialShortage;
